import imp,os
LOAD_PLUGINS = ["local","amazon"]

class Barcode:
	barcode = ""
	title = ""
	fields = {}
	
	def __init__(self, barcode = "", title = "", fields={}):
		self.barcode = barcode
		self.title = title
		self.fields = fields
		
	def __repr__(self):
		return "<Barcode '%s'>" % self.title

class BasePlugin:
	def getBarcode(self, barcode):
		return Barcode()

class Cache:
	lst = list()
	
	def __init__(self, maxitems):
		self.maxitems = maxitems
	
	def __repr__(self):
		return "<Cache : %s>" % ', '.join([obj[0] for obj in self.lst])
		
	def getBarcode(self, barcode):
		for obj in self.lst:
			if obj[0] == barcode:
				return obj[1]
		return None
	
	def addBarcode(self, barcode):
		if not self.getBarcode(barcode.barcode):
			if len(self.lst) >= self.maxitems:
				del self.lst[0]
		else:
			for obj in self.lst:
				if obj[0] == barcode.barcode:
					del self.lst[self.lst.index(obj)] # We update the record
					
		self.lst.append((barcode.barcode, barcode))

CACHE = Cache(50) # 50 items size			

def makeCall(callname, arg, plugins = LOAD_PLUGINS):
	for plugin in plugins:
		plugmodule = imp.load_source(plugin+"Plugin", os.path.join(os.path.dirname(__file__), plugin+"Plugin.py"))
		
		mainclass = getattr(plugmodule,plugin.capitalize())()
		barcode = getattr(mainclass,callname)(arg) # TODO : Implement several args
		
		if barcode != None:
			return barcode
	return None
	
def getBarcode(barcode):
	barcodeobj = CACHE.getBarcode(barcode)
	if barcodeobj:
		return barcodeobj
	else:
		return getBarcodeByPlugin(barcode)

# Warning ! We don't have cache with it !
def getBarcodeByPlugin(barcode, plugins = LOAD_PLUGINS):
	barcodeobj = makeCall("getBarcode", barcode, plugins)
	if barcodeobj: CACHE.addBarcode(barcodeobj)
	return barcodeobj
